<?php

/**
 * Description of multiCURL
 *
 * @author Gvozd
 */
require_once(dirname(__FILE__) . '/Task.php');
require_once(dirname(__FILE__) . '/CURLManager.php');

class multiCURL extends Task {

    public $ch = null;
    public $result = null;
    public $info = null;
    public $error = array();
    public $setopt = array();
    public $headerfile = NULL;
    
    /**
     * @var Deferred
     */
    public $startFilter = NULL;
    
    /**
     * @var Deferred
     */
    public $endFilter = NULL;

    function __construct($url) {
        $this->startFilter = new Deferred();
        $this->endFilter = new Deferred();
        
        $this->url = $url;
        //$this->headerfile = tmpfile();
        $this->setopt_array(array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 20,
            //CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_HTTPHEADER => array(
                'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Encoding: deflate',
            ),
            CURLOPT_ENCODING => "",
            CURLOPT_SSL_VERIFYPEER => false,
            //CURLINFO_HEADER_OUT => true,
            //CURLOPT_WRITEHEADER => $this->headerfile
        ));
    }

    function __destruct() {
        //echo "Destruct<br>\n";
    }

    /**
     *
     * @param array $options CURL options
     */
    public function setopt_array($options) {
        foreach ($options as $key => $value) {
            $this->setopt[$key] = $value;
        }
    }
    
    public function applyActions($actions) {
        foreach($actions as $name => $action) {
            try {
                call_user_func($action, $this);
            } catch (Exception $e) {
                var_dump("Catched Exception in $name action");
                var_dump($e->getMessage());
                die();
            }
        }
        
    }

    public function startExecution() {
        $this->startFilter->addBoth(array($this, 'start'));
        $this->startFilter->callback(NULL);
    }
    public function start($arg) {
        $this->ch = curl_init($this->url);
        curl_setopt_array($this->ch, $this->setopt);
        $curlMH = CURLManager::getInstance();
        $curlMH->addTask($this);
        $curlMH->init();
        return $arg;
    }

}